﻿using HY.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Infrastructure;
using WebApi.Model;
using WebApi.ViewModel;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class GPutOnRecordController : BaseController
    {
        public GPutOnRecordController(ILogger<GPutOnRecordController> logger) : base(logger)
        {

        }

        /// <summary>
        /// 获取购买备案信息分页列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("GetPageList")]
        public async Task<ReturnModel> GetPageList(QueryGPutOnRecordVM model)
        {
            try
            {
                Expression<Func<GPutOnRecord, bool>> filter = e => true;
                if (!string.IsNullOrEmpty(model.GNumber))
                    filter = filter.And(c => c.GNumber.Contains(model.GNumber));
                if (!string.IsNullOrEmpty(model.GCompany))
                    filter = filter.And(c => c.GCompany.Contains(model.GCompany));
                if (model.BeginTime != null)
                    filter = filter.And(c => model.BeginTime <= c.EndDate);
                if (model.EndTime != null)
                    filter = filter.And(c => model.EndTime >= c.EndDate);
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel { PageIndex = model.PageIndex, PageSize = model.PageSize };
                var data = await DbHelper.GPutOnRecord.GetPageListAsync(filter, pageModel);
                return new ReturnModel { Count = pageModel.TotalCount, Data = data };
            }
            catch (Exception ex)
            {
                LogToDB("Monitor", "查询", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(GetPageList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(GPutOnRecordController)}/{nameof(GetPageList)}", ex);
            }
        }

        [HttpPost("Add")]
        public async Task<ReturnModel> Add(GPutOnRecord model)
        {
            model.CreatTime = DateTime.Now;
            return await Save(model, true);
        }

        [HttpPost("Update")]
        public async Task<ReturnModel> Update(GPutOnRecord model)
        {
            return await Save(model, false);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isInsert"></param>
        /// <returns></returns>
        private async Task<ReturnModel> Save(GPutOnRecord model, bool isInsert)
        {
            Model.Log log = new Model.Log();
            log.TableName = nameof(GPutOnRecord);
            log.OpeResult = "成功";
            log.OpeDetail = JsonConvert.SerializeObject(model);
            try
            {
                model.PlateList = model.PlateList?.Replace('，', ',').Replace(" ", "");

                if (DbHelper.GPutOnRecord.IsAny(c => c.Enable == model.Enable && c.GCompany == model.GCompany && c.Id != model.Id))
                    return logger.Code_202("所选收货单位存在已启用的购买备案号");
                else if (DbHelper.GPutOnRecord.IsAny(c => c.Id != model.Id && c.GNumber == model.GNumber))
                    return logger.Code_202("购买备案号已存在");
                else if (isInsert)
                {
                    log.OpeType = "新增";
                    await DbHelper.GPutOnRecord.InsertAsync(model);
                }
                else
                {
                    log.OpeType = "修改";
                    GPutOnRecord old = DbHelper.GPutOnRecord.GetById(model.Id);
                    log.OpeDetail += $"修改前:{JsonConvert.SerializeObject(old)}";
                    if (model.Enable.Value)
                    {
                        using var tran = DbHelper.Db.UseTran();
                        string checkGoodsName = string.Empty;
                        DateTime updateTime = DateTime.Now;
                        log.Remark += $"{updateTime:yyyy-MM-dd HH:mm:ss}:";
                        if (!old.Enable925 && model.Enable925)
                        {
                            checkGoodsName = AppSetting.GetValue("WeighParams:H2SO4_925", "");
                            int totalWeight = DbHelper.Db.Queryable<YRecord>().Where(it => it.GNumber == model.GNumber && it.GoodsName == checkGoodsName && SqlFunc.IsNull(it.Price, 0m) == 0m).Sum(it => it.Weight ?? 0);
                            if (totalWeight > 0)
                            {
                                DbHelper.Db.Updateable<YRecord>().SetColumns(it => new YRecord { Price = model.Price925, UpdateTime = updateTime }).Where(it => it.GNumber == model.GNumber && it.GoodsName == checkGoodsName && SqlFunc.IsNull(it.Price, 0m) == 0m).ExecuteCommand();
                                model.GBalance -= totalWeight * model.Price925;
                                log.Remark += $"{checkGoodsName}价格启用，更新运输记录价格;";
                            }
                        }
                        if (!old.Enable98 && model.Enable98)
                        {
                            checkGoodsName = AppSetting.GetValue("WeighParams:H2SO4_98", "");
                            int totalWeight = DbHelper.Db.Queryable<YRecord>().Where(it => it.GNumber == model.GNumber && it.GoodsName == checkGoodsName && SqlFunc.IsNull(it.Price, 0m) == 0m).Sum(it => it.Weight ?? 0);
                            if (totalWeight > 0)
                            {
                                DbHelper.Db.Updateable<YRecord>().SetColumns(it => new YRecord { Price = model.Price98, UpdateTime = updateTime }).Where(it => it.GNumber == model.GNumber && it.GoodsName == checkGoodsName && SqlFunc.IsNull(it.Price, 0m) == 0m).ExecuteCommand();
                                model.GBalance -= totalWeight * model.Price98;
                                log.Remark += $"{checkGoodsName}价格启用，更新运输记录价格;";
                            }
                        }
                        if (!old.Enable1045 && model.Enable1045)
                        {
                            checkGoodsName = AppSetting.GetValue("WeighParams:H2SO4_1045", "");
                            int totalWeight = DbHelper.Db.Queryable<YRecord>().Where(it => it.GNumber == model.GNumber && it.GoodsName == checkGoodsName && SqlFunc.IsNull(it.Price, 0m) == 0m).Sum(it => it.Weight ?? 0);
                            if (totalWeight > 0)
                            {
                                DbHelper.Db.Updateable<YRecord>().SetColumns(it => new YRecord { Price = model.Price1045, UpdateTime = updateTime }).Where(it => it.GNumber == model.GNumber && it.GoodsName == checkGoodsName && SqlFunc.IsNull(it.Price, 0m) == 0m).ExecuteCommand();
                                model.GBalance -= totalWeight * model.Price1045;
                                log.Remark += $"{checkGoodsName}价格启用，更新运输记录价格;";
                            }
                        }
                        await DbHelper.Db.Updateable(model).IgnoreColumns(it => it.CreatTime).ExecuteCommandAsync();
                        tran.CommitTran();
                    }
                    else
                        await DbHelper.Db.Updateable(model).IgnoreColumns(it => it.CreatTime).ExecuteCommandAsync();
                }
                LogToDB(log);
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                log.OpeResult = "异常";
                log.Remark += ex.ToString();
                LogToDB(log);
                return logger.ErrorModel(nameof(GPutOnRecordController) + "-" + nameof(Save), ex);
            }
        }

        [HttpPost("Delete/{id}")]
        public async Task<ReturnModel> Delete(int id)
        {
            try
            {
                GPutOnRecord model = DbHelper.GPutOnRecord.GetById(id);
                await DbHelper.GPutOnRecord.DeleteAsync(it => it.Id == id);
                LogToDB("GPutOnRecord", "删除", $"参数：{id},删除数据：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("GPutOnRecord", "删除", $"参数：{id}", "异常", $"{nameof(Delete)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(GPutOnRecordController)}/{nameof(Delete)}", ex);
            }
        }

        /// <summary>
        /// 获取运输单位下拉框数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("SelectList")]
        public async Task<ReturnModel> SelectList()
        {
            try
            {
                var list = await DbHelper.GPutOnRecord.AsQueryable().Select(it => it.GNumber).ToListAsync();
                return new ReturnModel { Count = list.Count, Data = list };
            }
            catch (Exception ex)
            {
                return logger.ErrorModel($"{nameof(GPutOnRecordController)}/{nameof(SelectList)}", ex);
            }
        }
    }
}
